package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.dto.ChatMessageDTO;
import com.zenithmind.chat.pojo.query.ChatMessageQuery;
import com.zenithmind.chat.pojo.vo.ChatMessageVO;
import com.zenithmind.chat.pojo.vo.ChatUserVO;
import com.zenithmind.chat.service.ChatMessageService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 聊天消息控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/chat/message")
@RequiredArgsConstructor
@Tag(name = "聊天消息管理", description = "聊天消息相关接口")
public class ChatMessageController {

    private final ChatMessageService messageService;

    @GetMapping("/page")
    @Operation(summary = "分页查询消息列表", description = "支持多条件查询消息")
    public Result<PageResult<ChatMessageVO>> getMessagePage(@Validated ChatMessageQuery query) {
        String userId = UserContext.getUserId();
        PageResult<ChatMessageVO> result = messageService.getMessagePage(query, userId);
        return Result.success(result);
    }

    @GetMapping("/group/{groupId}")
    @Operation(summary = "获取群组消息", description = "获取指定群组的消息列表")
    public Result<List<ChatMessageVO>> getGroupMessages(
            @Parameter(description = "群组ID") @PathVariable String groupId,
            @Parameter(description = "最后消息ID") @RequestParam(required = false) String lastMessageId,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<ChatMessageVO> messages = messageService.getGroupMessages(groupId, userId, lastMessageId, limit);
        return Result.success(messages);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取消息详情", description = "根据ID获取消息详细信息")
    public Result<ChatMessageVO> getMessageById(
            @Parameter(description = "消息ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        ChatMessageVO message = messageService.getMessageById(id, userId);
        return Result.success(message);
    }

    @PostMapping
    @Operation(summary = "发送消息", description = "发送聊天消息")
    public Result<String> sendMessage(@Validated @RequestBody ChatMessageDTO messageDTO) {
        String userId = UserContext.getUserId();
        String messageId = messageService.sendMessage(messageDTO, userId);
        return Result.success(messageId);
    }

    @PostMapping("/{id}/recall")
    @Operation(summary = "撤回消息", description = "撤回已发送的消息")
    public Result<Boolean> recallMessage(
            @Parameter(description = "消息ID") @PathVariable String id,
            @Parameter(description = "撤回原因") @RequestParam(required = false) String reason) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.recallMessage(id, userId, reason);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除消息", description = "删除指定消息")
    public Result<Boolean> deleteMessage(
            @Parameter(description = "消息ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.deleteMessage(id, userId);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除消息", description = "批量删除多条消息")
    public Result<Boolean> deleteMessagesBatch(@RequestBody List<String> ids) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.deleteMessagesBatch(ids, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/pin")
    @Operation(summary = "置顶消息", description = "将消息置顶")
    public Result<Boolean> pinMessage(
            @Parameter(description = "消息ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.pinMessage(id, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/unpin")
    @Operation(summary = "取消置顶", description = "取消消息置顶")
    public Result<Boolean> unpinMessage(
            @Parameter(description = "消息ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.unpinMessage(id, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/like")
    @Operation(summary = "点赞消息", description = "为消息点赞")
    public Result<Boolean> likeMessage(
            @Parameter(description = "消息ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.likeMessage(id, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/unlike")
    @Operation(summary = "取消点赞", description = "取消消息点赞")
    public Result<Boolean> unlikeMessage(
            @Parameter(description = "消息ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.unlikeMessage(id, userId);
        return Result.success(result);
    }

    @PostMapping("/read")
    @Operation(summary = "标记已读", description = "标记消息为已读")
    public Result<Boolean> markMessagesAsRead(@RequestBody List<String> messageIds) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.markMessagesAsRead(messageIds, userId);
        return Result.success(result);
    }

    @PostMapping("/group/{groupId}/read-all")
    @Operation(summary = "全部已读", description = "标记群组所有消息为已读")
    public Result<Boolean> markGroupMessagesAsRead(
            @Parameter(description = "群组ID") @PathVariable String groupId) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.markGroupMessagesAsRead(groupId, userId);
        return Result.success(result);
    }

    @GetMapping("/{id}/read-users")
    @Operation(summary = "已读用户", description = "获取消息已读用户列表")
    public Result<List<ChatUserVO>> getMessageReadUsers(
            @Parameter(description = "消息ID") @PathVariable String id) {
        List<ChatUserVO> users = messageService.getMessageReadUsers(id);
        return Result.success(users);
    }

    @GetMapping("/{id}/unread-users")
    @Operation(summary = "未读用户", description = "获取消息未读用户列表")
    public Result<List<ChatUserVO>> getMessageUnreadUsers(
            @Parameter(description = "消息ID") @PathVariable String id) {
        List<ChatUserVO> users = messageService.getMessageUnreadUsers(id);
        return Result.success(users);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索消息", description = "根据关键词搜索消息")
    public Result<List<ChatMessageVO>> searchMessages(
            @Parameter(description = "群组ID") @RequestParam String groupId,
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "消息类型") @RequestParam(required = false) Integer messageType,
            @Parameter(description = "发送者ID") @RequestParam(required = false) String senderId,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        List<ChatMessageVO> messages = messageService.searchMessages(
            groupId, keyword, messageType, senderId, startTime, endTime, limit);
        return Result.success(messages);
    }

    @GetMapping("/group/{groupId}/pinned")
    @Operation(summary = "置顶消息", description = "获取群组置顶消息列表")
    public Result<List<ChatMessageVO>> getPinnedMessages(
            @Parameter(description = "群组ID") @PathVariable String groupId) {
        List<ChatMessageVO> messages = messageService.getPinnedMessages(groupId);
        return Result.success(messages);
    }

    @GetMapping("/mention")
    @Operation(summary = "@我的消息", description = "获取@我的消息列表")
    public Result<List<ChatMessageVO>> getMentionMessages(
            @Parameter(description = "群组ID") @RequestParam(required = false) String groupId,
            @Parameter(description = "是否已读") @RequestParam(required = false) Boolean isRead) {
        String userId = UserContext.getUserId();
        List<ChatMessageVO> messages = messageService.getMentionMessages(userId, groupId, isRead);
        return Result.success(messages);
    }

    @GetMapping("/group/{groupId}/unread-count")
    @Operation(summary = "未读数量", description = "获取群组未读消息数量")
    public Result<Integer> getUnreadMessageCount(
            @Parameter(description = "群组ID") @PathVariable String groupId) {
        String userId = UserContext.getUserId();
        Integer count = messageService.getUnreadMessageCount(groupId, userId);
        return Result.success(count);
    }

    @GetMapping("/group/{groupId}/latest")
    @Operation(summary = "最新消息", description = "获取群组最新消息")
    public Result<ChatMessageVO> getLatestMessage(
            @Parameter(description = "群组ID") @PathVariable String groupId) {
        String userId = UserContext.getUserId();
        ChatMessageVO message = messageService.getLatestMessage(groupId, userId);
        return Result.success(message);
    }

    @PostMapping("/system")
    @Operation(summary = "发送系统消息", description = "发送系统消息")
    public Result<String> sendSystemMessage(
            @Parameter(description = "群组ID") @RequestParam String groupId,
            @Parameter(description = "消息内容") @RequestParam String content,
            @Parameter(description = "消息类型") @RequestParam(defaultValue = "6") Integer messageType) {
        String messageId = messageService.sendSystemMessage(groupId, content, messageType);
        return Result.success(messageId);
    }

    @PostMapping("/{id}/forward")
    @Operation(summary = "转发消息", description = "转发消息到其他群组")
    public Result<Boolean> forwardMessage(
            @Parameter(description = "消息ID") @PathVariable String id,
            @RequestBody List<String> targetGroupIds) {
        String userId = UserContext.getUserId();
        Boolean result = messageService.forwardMessage(id, targetGroupIds, userId);
        return Result.success(result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "消息统计", description = "获取消息统计信息")
    public Result<Object> getMessageStatistics(
            @Parameter(description = "群组ID") @RequestParam(required = false) String groupId,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {
        Object statistics = messageService.getMessageStatistics(groupId, startTime, endTime);
        return Result.success(statistics);
    }

    @DeleteMapping("/clean")
    @Operation(summary = "清理过期消息", description = "清理指定天数前的消息")
    public Result<Integer> cleanExpiredMessages(
            @Parameter(description = "保留天数") @RequestParam(defaultValue = "30") Integer days) {
        Integer count = messageService.cleanExpiredMessages(days);
        return Result.success(count);
    }
}
